package cn.lblbc.calc

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.math.BigDecimal
import java.math.MathContext
import java.math.RoundingMode
import com.google.android.material.button.MaterialButton

class CalculatorActivity : AppCompatActivity() {
    private lateinit var display: TextView
    private lateinit var history: TextView
    private var currentValue = ""
    private var firstValue = BigDecimal.ZERO
    private var operator = ""
    private var isNewOperation = true
    private var isError = false
    private var currentTheme = THEME_CYBERPUNK
    
    companion object {
        const val PREFS_NAME = "CalculatorPrefs"
        const val THEME_KEY = "SelectedTheme"
        const val THEME_CYBERPUNK = "cyberpunk"
        const val THEME_CLASSIC = "classic"
        const val THEME_OCEAN = "ocean"
        const val THEME_SUNSET = "sunset"
        const val THEME_FOREST = "forest"
        const val THEME_MINIMALIST = "minimalist"
        const val THEME_DEEPSPACE = "deepspace"
        const val THEME_CRT = "crt"
        const val THEME_CANDY = "candy"
        const val THEME_FIRE = "fire"
        
        val THEME_NAMES = arrayOf(
            "赛博朋克", "经典暗色", "海洋", "日落", "森林",
            "极简白色", "深空黑", "复古CRT", "粉彩糖果", "火焰"
        )
        
        val THEME_KEYS = arrayOf(
            THEME_CYBERPUNK, THEME_CLASSIC, THEME_OCEAN, THEME_SUNSET, THEME_FOREST,
            THEME_MINIMALIST, THEME_DEEPSPACE, THEME_CRT, THEME_CANDY, THEME_FIRE
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        // 应用保存的主题
        applySavedTheme()
        
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_calculator)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        display = findViewById(R.id.display)
        history = findViewById(R.id.history)
        display.text = "0"
        
        // 找到并设置三点按钮的点击事件
        val settingsButton = findViewById<ImageView>(R.id.settings_button)
        settingsButton.setOnClickListener {
            val intent = Intent(this, SettingsActivity::class.java)
            startActivity(intent)
        }
    }
    
    override fun onResume() {
        super.onResume()
        
        // 获取保存的主题
        val prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
        val savedTheme = prefs.getString(THEME_KEY, THEME_CYBERPUNK) ?: THEME_CYBERPUNK
        
        // 检查主题是否已更改
        if (savedTheme != currentTheme) {
            // 重新创建Activity以应用新主题
            recreate()
        }
    }
    
    private fun applySavedTheme() {
        val prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
        currentTheme = prefs.getString(THEME_KEY, THEME_CYBERPUNK) ?: THEME_CYBERPUNK
        
        when (currentTheme) {
            THEME_CYBERPUNK -> setTheme(R.style.Theme_Calculator_Cyberpunk)
            THEME_CLASSIC -> setTheme(R.style.Theme_Calculator_Classic)
            THEME_OCEAN -> setTheme(R.style.Theme_Calculator_Ocean)
            THEME_SUNSET -> setTheme(R.style.Theme_Calculator_Sunset)
            THEME_FOREST -> setTheme(R.style.Theme_Calculator_Forest)
            THEME_MINIMALIST -> setTheme(R.style.Theme_Calculator_Minimalist)
            THEME_DEEPSPACE -> setTheme(R.style.Theme_Calculator_DeepSpace)
            THEME_CRT -> setTheme(R.style.Theme_Calculator_CRT)
            THEME_CANDY -> setTheme(R.style.Theme_Calculator_Candy)
            THEME_FIRE -> setTheme(R.style.Theme_Calculator_Fire)
        }
    }
    
    private fun saveAndApplyTheme(theme: String) {
        // 保存主题选择
        val prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
        prefs.edit().putString(THEME_KEY, theme).apply()
        
        // 更新当前主题
        currentTheme = theme
        
        // 重新创建Activity以应用新主题
        recreate()
    }

    fun onDigitClick(view: View) {
        if (isError) {
            resetCalculator()
        }
        
        if (isNewOperation) {
            currentValue = ""
            isNewOperation = false
        }
        
        val digit = (view as Button).text.toString()
        
        // 防止数字过长
        if (currentValue.length >= 15) {
            Toast.makeText(this, "Number too long", Toast.LENGTH_SHORT).show()
            return
        }
        
        currentValue += digit
        updateDisplay()
        
        // 添加赛博朋克风格的反馈效果
        view.animate().scaleX(0.9f).scaleY(0.9f).setDuration(50).withEndAction {
            view.animate().scaleX(1.0f).scaleY(1.0f).setDuration(50)
        }
    }

    fun onDoubleZeroClick(view: View) {
        if (isError) {
            resetCalculator()
        }
        
        if (isNewOperation) {
            currentValue = ""
            isNewOperation = false
        }
        
        // 防止数字过长
        if (currentValue.length >= 14) { // 00需要两个字符位置
            Toast.makeText(this, "Number too long", Toast.LENGTH_SHORT).show()
            return
        }
        
        // 避免以00开头的无效数字（除非当前值已经是0）
        if (currentValue.isEmpty()) {
            currentValue = "0"
        } else {
            currentValue += "00"
        }
        
        updateDisplay()
        
        // 添加赛博朋克风格的反馈效果
        view.animate().scaleX(0.9f).scaleY(0.9f).setDuration(50).withEndAction {
            view.animate().scaleX(1.0f).scaleY(1.0f).setDuration(50)
        }
    }

    fun onOperatorClick(view: View) {
        if (isError) return
        
        val op = (view as Button).text.toString()

        if (currentValue.isNotEmpty()) {
            if (operator.isNotEmpty() && !isNewOperation) {
                onEqualsClick(view)
            } else {
                firstValue = try {
                    BigDecimal(currentValue)
                } catch (e: NumberFormatException) {
                    showError("Invalid number")
                    return
                }
                updateHistory(firstValue.toString())
            }
        } else if ((op == "−" || op == "-") && currentValue.isEmpty()) {
            currentValue = "-"
            updateDisplay()
            return
        } else if (currentValue.isEmpty()) {
            // 如果没有输入数字就点击运算符，使用显示的值作为第一个数
            try {
                firstValue = BigDecimal(display.text.toString())
            } catch (e: NumberFormatException) {
                showError("Invalid number")
                return
            }
            updateHistory(firstValue.toString())
        }

        operator = when (op) {
            "÷" -> "/"
            "×" -> "*"
            "−" -> "-"
            else -> op
        }
        
        updateHistory(" $operator ")
        isNewOperation = true
        
        // 添加赛博朋克风格的反馈效果
        view.animate().scaleX(0.9f).scaleY(0.9f).setDuration(50).withEndAction {
            view.animate().scaleX(1.0f).scaleY(1.0f).setDuration(50)
        }
    }

    fun onEqualsClick(view: View) {
        if (isError || currentValue.isEmpty() || operator.isEmpty()) return

        try {
            val secondValue = BigDecimal(currentValue)
            val result = when (operator) {
                "+" -> firstValue.add(secondValue)
                "-" -> firstValue.subtract(secondValue)
                "*" -> firstValue.multiply(secondValue)
                "/" -> {
                    if (secondValue.compareTo(BigDecimal.ZERO) == 0) {
                        showError("Cannot divide by zero")
                        return
                    }
                    // 限制除法精度以避免无限小数
                    firstValue.divide(secondValue, MathContext(15, RoundingMode.HALF_UP))
                }
                else -> secondValue
            }

            // 更新历史记录
            updateHistory(" $currentValue =")
            
            // 格式化结果，限制长度
            currentValue = formatResult(result)
            if (currentValue.length > 15) {
                showError("Result too long")
                return
            }
            
            updateDisplay()
            
            operator = ""
            isNewOperation = true
            
            // 添加结果到历史记录
            updateHistory("\n= $currentValue\n")
            
            // 添加赛博朋克风格的反馈效果
            view.animate().scaleX(0.9f).scaleY(0.9f).setDuration(50).withEndAction {
                view.animate().scaleX(1.0f).scaleY(1.0f).setDuration(50)
            }
        } catch (e: Exception) {
            showError("Calculation error")
        }
    }

    fun onClearClick(view: View) {
        resetCalculator()
        
        // 添加赛博朋克风格的反馈效果
        view.animate().scaleX(0.9f).scaleY(0.9f).setDuration(50).withEndAction {
            view.animate().scaleX(1.0f).scaleY(1.0f).setDuration(50)
        }
    }

    fun onDecimalClick(view: View) {
        if (isError) {
            resetCalculator()
        }
        
        if (isNewOperation) {
            currentValue = "0"
            isNewOperation = false
        }
        
        // 检查是否已经包含小数点
        if (!currentValue.contains(".")) {
            // 检查数字长度
            if (currentValue.length >= 15) {
                Toast.makeText(this, "Number too long", Toast.LENGTH_SHORT).show()
                return
            }
            
            currentValue += "."
            updateDisplay()
        }
        
        // 添加赛博朋克风格的反馈效果
        view.animate().scaleX(0.9f).scaleY(0.9f).setDuration(50).withEndAction {
            view.animate().scaleX(1.0f).scaleY(1.0f).setDuration(50)
        }
    }
    
    fun onToggleSignClick(view: View) {
        if (isError) return
        
        if (currentValue.isNotEmpty()) {
            try {
                // 处理负号在开头的情况
                if (currentValue.startsWith("-")) {
                    currentValue = currentValue.substring(1)
                } else {
                    currentValue = "-" + currentValue
                }
                updateDisplay()
            } catch (e: Exception) {
                showError("Invalid operation")
            }
        } else {
            // 如果没有输入数字，对当前显示的数字取反
            try {
                val currentDisplay = display.text.toString()
                val newValue = if (currentDisplay.startsWith("-")) {
                    currentDisplay.substring(1)
                } else if (currentDisplay != "0") {
                    "-" + currentDisplay
                } else {
                    currentDisplay // 0的负数还是0
                }
                
                display.text = newValue
                // 设置currentValue以便后续计算使用
                currentValue = newValue
                isNewOperation = false
            } catch (e: Exception) {
                showError("Invalid operation")
            }
        }
        
        // 添加赛博朋克风格的反馈效果
        view.animate().scaleX(0.9f).scaleY(0.9f).setDuration(50).withEndAction {
            view.animate().scaleX(1.0f).scaleY(1.0f).setDuration(50)
        }
    }
    
    fun onPercentClick(view: View) {
        if (isError) return
        
        try {
            val value = if (currentValue.isNotEmpty()) {
                BigDecimal(currentValue)
            } else {
                BigDecimal(display.text.toString())
            }
            
            val result = value.divide(BigDecimal("100"), MathContext(15, RoundingMode.HALF_UP))
            currentValue = formatResult(result)
            if (currentValue.length > 15) {
                showError("Result too long")
                return
            }
            
            updateDisplay()
            isNewOperation = true
        } catch (e: NumberFormatException) {
            showError("Invalid number")
        } catch (e: Exception) {
            showError("Calculation error")
        }
        
        // 添加赛博朋克风格的反馈效果
        view.animate().scaleX(0.9f).scaleY(0.9f).setDuration(50).withEndAction {
            view.animate().scaleX(1.0f).scaleY(1.0f).setDuration(50)
        }
    }
    
    private fun updateDisplay() {
        display.text = if (currentValue.isEmpty()) "0" else currentValue
    }
    
    private fun updateHistory(text: String) {
        val currentHistory = history.text.toString()
        history.text = currentHistory + text
        // 滚动到底部
        history.post {
            history.scrollBy(0, 1000) // 向下滚动足够距离
        }
    }
    
    private fun formatResult(result: BigDecimal): String {
        // 移除尾随零
        val stripped = result.stripTrailingZeros()
        
        // 如果是整数，返回整数形式
        return if (stripped.scale() <= 0) {
            stripped.toBigInteger().toString()
        } else {
            // 限制小数位数
            val scaled = stripped.setScale(10, RoundingMode.HALF_UP).stripTrailingZeros()
            if (scaled.scale() <= 0) {
                scaled.toBigInteger().toString()
            } else {
                scaled.toPlainString()
            }
        }
    }
    
    private fun showError(message: String = "Error") {
        display.text = message
        isError = true
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }
    
    private fun resetCalculator() {
        currentValue = ""
        firstValue = BigDecimal.ZERO
        operator = ""
        isNewOperation = true
        isError = false
        display.text = "0"
        // 不清空历史记录，让用户可以查看之前的计算
    }
}